package com.smp.handler;

import com.smp.exceptions.BusinessException;
import lombok.extern.slf4j.Slf4j;
import org.springframework.http.HttpMethod;
import org.springframework.http.HttpStatus;
import org.springframework.http.client.ClientHttpResponse;
import org.springframework.web.client.ResponseErrorHandler;

import java.io.IOException;
import java.net.URI;

/**
 * @author: fangxiaoyu
 * @date: 2021/6/15
 * @description:
 **/
@Slf4j
public class MyRestErrorHandler implements ResponseErrorHandler {
    /**
     * 判断返回结果response是否异常结果
     * 主要是去检查response 的HTTP status
     * 仿造DefaultResponseErrorHandler实现即可
     *
     * @param clientHttpResponse
     * @return
     * @throws IOException
     */
    @Override
    public boolean hasError(ClientHttpResponse clientHttpResponse) throws IOException {
        int rawStatusCode = clientHttpResponse.getRawStatusCode();
        HttpStatus statusCode = HttpStatus.resolve(rawStatusCode);
        return (null != statusCode ? statusCode.isError() : hasError(rawStatusCode));
    }

    protected boolean hasError(int unknownStatusCode) {
        HttpStatus.Series series = HttpStatus.Series.resolve(unknownStatusCode);
        return (series == HttpStatus.Series.CLIENT_ERROR || series == HttpStatus.Series.SERVER_ERROR);
    }

    @Override
    public void handleError(ClientHttpResponse clientHttpResponse) throws IOException {
        // 这里可以实现遇到的error进行合理的处理
        // TODO 将接口的请求的异常信息持久化
        log.error(clientHttpResponse.toString());
        throw new BusinessException("远程调用异常：" + clientHttpResponse.getStatusCode());
    }

    @Override
    public void handleError(URI url, HttpMethod method, ClientHttpResponse response) throws IOException {
        log.error("远程调用 {} ，method：{}, 返回结果：{}", url, method.name(), response.getStatusCode());
        this.handleError(response);
    }

}
